type TKeyCodeMap = Record<string, string | number | (string | number)[]>;

// 键码映射
let keyCodeMap: TKeyCodeMap = {
	ESC: 27,
	TAB: 9,
	ENTER: 13,
	LEFT: 37,
	UP: 38,
	RIGHT: 39,
	DOWN: 40,
	INSERT: 45,
	DELETE: 46,
	BACKSPACE: 8,
	ADD: 107,
	DOT: [102, 110],
	F12: 123,
};

// 设置字母的键码
(function setLetterCode() {
	let letterCodeIndex = 65;
	const letterCodeMap: TKeyCodeMap = {};
	const LETTER_CODE_END = 90;
	while (letterCodeIndex <= LETTER_CODE_END) {
		const code = String.fromCharCode(letterCodeIndex).toUpperCase();
		letterCodeMap[code] = letterCodeIndex;
		letterCodeIndex++;
	}
	keyCodeMap = { ...keyCodeMap, ...letterCodeMap };
})();

// 设置数字的键码
(function setNumberCode() {
	let codeIndex = 48;
	const numberCodeMap: TKeyCodeMap = {};
	// 主键盘数字
	while (codeIndex <= 57) {
		const code = String.fromCharCode(codeIndex).toUpperCase();
		numberCodeMap[code] = [codeIndex];
		codeIndex++;
	}

	// 小键盘数字
	codeIndex = 96;
	while (codeIndex <= 105) {
		const code = codeIndex - 96;
		if (Array.isArray(numberCodeMap[code])) {
			(numberCodeMap[code] as any[]).push(codeIndex);
		}
		codeIndex++;
	}
	keyCodeMap = { ...keyCodeMap, ...numberCodeMap };
})();

/**
 * 根据code序列化成中文A-Z 0-9
 * @param code
 * @returns
 */
const parseKeyCode = (code: number): string => {
	let keyCode = '';
	for (let key in keyCodeMap) {
		if (Array.isArray(keyCodeMap[key])) {
			if ((keyCodeMap[key] as any[]).includes(code)) {
				keyCode = key;
				break;
			}
		} else {
			if (keyCodeMap[key] === code) {
				keyCode = key;
				break;
			}
		}
	}
	return keyCode;
};

export { parseKeyCode };
export default keyCodeMap;
